package com.tul.exercise.base.clazz.base.eg4;

import java.util.ArrayList;
import java.util.List;

import static com.tul.exercise.base.utils.Print.print;

/**
 * @author tul
 * 《java编程思想》 14章 示例4:泛化的class引用
 *
 */
public class FilledList<T> {
    // 对象类型
    private Class<T> type;

    // 构造函数
    public FilledList(Class<T> type) {
        this.type = type;
    }

    /**
     *  创建对象实例list
     * @param num 个数
     * @return 实例list
     */
    public List<T> create(int num) {
        List<T> result = new ArrayList<>();
        try {
            for(int i=0;i<num;i++) {
                result.add(type.newInstance());
            }
        } catch (IllegalAccessException | InstantiationException e) {
            print("实例化异常," + type.getSimpleName());
        }
        return result;
    }

    public static void main(String[] args) {
        FilledList<CountedInteger> filledList = new FilledList<CountedInteger>(CountedInteger.class);

        print(filledList.create(10));
    }
}
